package com.itheima.controller;

import com.itheima.mapper.UserMapper;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    //--1--查询所有
    @GetMapping()
    public Result selectAll(){
        List<User> userList = userMapper.selectAll();
        System.out.println(userList);
        return new Result(1,userList,"OK");
    }

	//--2--分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable  int currentPage,@PathVariable int pageSize) throws IOException {
        //==当前第几页：得出 sql语句中的begin
        int begin=(currentPage-1)*pageSize;
        PageBean<User> pageBean=new PageBean<>();
        pageBean.setTotalCount(userMapper.selectCount());
        pageBean.setRows(userMapper.selectByPage(begin,pageSize));
        return new Result(1,pageBean,"OK");
    }

    //--3--添加
    @PostMapping
    public Result add(@RequestBody  User user) {
        if(userMapper.add(user)!=0){
            return new Result(1,null,"OK");
        }else {
            return new Result(0,null,"NO");
        }
    }

    //--4--id删除
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        if(userMapper.deleteById(id)!=0){
            return new Result(1,null,"OK");
        }else {
            return new Result(0,null,"NO");
        }
    }

    //--5--修改
    @PutMapping
    public Result update(@RequestBody User user) {
        if(userMapper.update(user)!=0){
            return new Result(1,null,"OK");
        }else {
            return new Result(0,null,"NO");
        }
    }

}
